    //
//  YMPopMenu.swift
//  YDOAProduct
//
//  Created by YDWY on 2017/6/29.
//  Copyright © 2017年 Allen. All rights reserved.
//

import UIKit

class YMPopMenu: UIView {

    var bgView : UIView? = nil //遮罩
    
    var mytabview : UITableView?
    var callBack : ((_ id: String , _ title : String)->Swift.Void)? = nil
    
    var dataSource : Array<[String : String]>? = nil
    init(frame: CGRect , dataSource : Array<[String : String]>){
        super.init(frame: frame)
        self.isUserInteractionEnabled = true
        bgView = UIView(frame: self.bounds)
        bgView?.backgroundColor = UIColor(white: 0.3, alpha:0.4)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(bgViewTap))
        

        bgView?.addGestureRecognizer(tap)
        
        bgView?.isUserInteractionEnabled = true
        self.addSubview(bgView!)
        
       
        mytabview = UITableView(frame: CGRect(x: 0, y:UIScreen.main.bounds.size.height - 200 , width:UIScreen.main.bounds.size.width , height: 200) , style: .plain)
        mytabview?.isUserInteractionEnabled = true
        mytabview?.delegate = self
        mytabview?.dataSource = self
        mytabview?.register(UITableViewCell.self, forCellReuseIdentifier: "popcell")
      
        self.addSubview(mytabview!)
        
        self.dataSource = dataSource
        
        
    }
    
    
    //点击事件
    @objc private func bgViewTap(tap : UITapGestureRecognizer){
        let point = tap.location(in: self)
        YMLog.log(item: "点击横坐标\(point.x) 纵坐标\(point.y)")
        YMLog.log(item: "背景被我点击了")

        self.removeFromSuperview()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

    
extension YMPopMenu: UITableViewDelegate,UITableViewDataSource{

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (dataSource?.count)!
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "popcell") else { return UITableViewCell() }
        cell.textLabel?.text = dataSource?[indexPath.row]["item"]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let data = dataSource?[indexPath.row],
              let title = data["item"],
              let id = data["id"]
            else {return }
        YMLog.log(item: "\(title) ==== \(id)")
        if (callBack != nil) {
            callBack!(id,title)
        }
        
        self.removeFromSuperview()
    }
    
    
}
    
